function [cvf, chf, chs, nwarn] = ConvertPixelToMM(frontbackdist, vertdp, vertds, bpmm, bby, ffrontbackdist, sfrontbackdist, kf, ks, bf, bs, df, ds, as, af, xf, yf, xs, ys)

load('videoprocessdata.mat');

nwarn = 0;

%buffer that things are allowed to go outside the range of the animals area. 
%For example a bird's tail might stick outside the cage.
buf = 15; %mm 

cvf = 0;
chf = 0;
chs = 0;

wrongcf = 0;


a = kf*bs-df*ks;
b = yf*ks-af*ks+bf*bs-df*ds-kf*ys+kf*as;
c = yf*ds-af*ds-bf*ys+bf*as;

z = b*b-4*a*c;

if z < 0

    cf = 0;
    cs = 0;
    
    nwarn = 2;
    
else
    d = sqrt(z);
    
    x1 = (-b+d)/(2*a);
    x2 = (-b-d)/(2*a);

    cf = 0;
    cs = 0;
        
    if x2 < 0
        cf = x1;
    elseif x1 < 0
        cf = x2;
    elseif x2 < -buf || x2 > (sfrontbackdist+buf)
        cf = x1;
    elseif x1 < -buf || x1 > (sfrontbackdist+buf)
        cf = x2;
    else
        nwarn = 3;
    end
    
    if cf < -buf || cf > (sfrontbackdist+buf)   
        cf = 0;
        nwarn = 4;        
    elseif cf < 0
        cf = 0.01;
    end
       
    
    if cf > 0
        cs = (ys-as-bs*cf)/(ds+ks*cf);
    end
    
    if cs < -buf || cs > (ffrontbackdist+buf)
        cf = 0;
        cs = 0;
        nwarn = 5;
    elseif cs < 0
        cs = 0.01;
    end        

end



dp = vertdp;
ds = vertds;

p = bpmm + (frontbackdist - cs)*dp;
sp = bby + (frontbackdist - cs)*ds;


cvf = (sp - xf)/p;


chf = cf;
chs = cs;

if cvf < 0 & cvf > -buf
    cvf = 0.01;
end




        
